package cn.sfa.controller.users;

import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.DateUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.ImageHepler;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.affixItem.SaleAffixItem;
import cn.sfa.entity.meeting.SaleMeeting;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.affix.AffixService;
import cn.sfa.service.login.LoginService;
import cn.sfa.service.meeting.MeetingService;

/**
 * 
* 类名称：HeadPhotoSetterController   
* 类描述： 头像设置处理类
* 创建人：LLY   
* 创建时间：2012-2-27  
* 修改人：LLY   
* 修改时间：2012-2-27   
* 修改备注：   
* @version
 */
@Controller
@RequestMapping("users/headPhoto/index")
public class HeadPhotoSetterController extends WebInitBinderContoller{

	Logger log = LoggerFactory.getLogger(HeadPhotoSetterController.class);
	@Autowired
	LoginService loginService;
	private String affixType = "USERPHOTO";
	@Autowired
	AffixService affixService;
	private Pagination pagination;//分页
	
	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}
	
	/**
	 * 转到个人信息
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping("/toUpload")
	public String toUpload( HttpServletRequest request,ModelMap map)
	{
		String defaultPic = "/images/imageCut/man.GIF";
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		String agentId = user.getUserAgentId();
		String photo=defaultPic;//默认图片
		List<SaleAffixItem> head=affixService.getAffix(affixType, agentId);
		for(SaleAffixItem affix:head)
		{
			if(affix.getIsTrue()!=null && affix.getIsTrue().equals("Y"))
			{
				photo=affix.getSALEAFFIXITEMFILEPATH();
				break;
			}
		}
		map.put("photo", photo);
		map.put("defaultPic", defaultPic);
		return "/users/uploadPhoto";
	}
	
	/**
	 * 转到设置头像
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping("/setPage")
	public String toSet( HttpServletRequest request,ModelMap map)
	{
		String defaultPic = "/images/imageCut/man.GIF";
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		
		List<SaleAffixItem> affixList = affixService.getAffix(affixType,user.getUserAgentId());
		for(SaleAffixItem agentAffix : affixList){
			if("Y".equals(agentAffix.getIsTrue())){
				defaultPic = agentAffix.getSALEAFFIXITEMFILEPATH();
			}
		}
		
		map.put("defaultPic", defaultPic);
		map.put("step", 1);
		return "/users/uploadPage";
	}
	
	/**
	 * 删除头像
	 * @throws IOException 
	 * 
	 * 
	 */
	@RequestMapping("/delete")
	public void delete( HttpServletRequest request,ModelMap map,HttpServletResponse response) throws IOException
	{
		String defaultPic = "/images/imageCut/man.GIF";
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		String agentId = user.getUserAgentId();
		String photo=defaultPic;//默认图片
		List<SaleAffixItem> head=affixService.getAffix(affixType, agentId);
		SaleAffixItem s=null;
		for(SaleAffixItem affix:head)
		{
			if(affix.getIsTrue()!=null && affix.getIsTrue().equals("Y"))
			{
				affix.setIsTrue("N");
				s=affix;
				break;
			} 
		}
		boolean flag=affixService.update(s);
		
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
 
            JSONObject temp = new JSONObject();
             
            temp.put("flag", flag);
            temp.put("photo", photo);
             
            PrintWriter out=response.getWriter();
	        out.print(temp.toString());
			out.flush();
			out.close();
	}
	
	
	 
	/**
	 * 设置头像
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping("/setPhoto")
	public void add( HttpServletRequest request,ModelMap map,
			HttpServletResponse response,
			@RequestParam(value="affixStr",required=false)String affixStr
			 ) throws Exception
	{
		
		PrintWriter out=response.getWriter(); 
		
		String isAffix=request.getParameter("isAffix"); 
		 String add="";
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		if(CommonUtil.isEmpty(isAffix))
		{
			 
			 
				try {
					//保存附件
					affixService.saveAffix(affixStr, "SALEUSERSLOGIN", user.getSaleUsersLoginId());
					add="头像设置成功！";
				} catch (Exception e) {
					add="头像设置失败！";
				}
	  
		}  
		add="请先上传您的照片，再进行设置";
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8"); 
        JSONObject temp = new JSONObject();
        temp.put("msg", add);
        out.print(temp.toString());
		out.flush();
		out.close();
	}

	/**
	 * 上传头像
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/upLoadImage")
	public String upLoadImage(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		// 应用程序的真实路径
		String path = request.getSession().getServletContext().getRealPath("/");
		String agentId = request.getParameter("agentId");
		String defaultPic = "/images/imageCut/man.GIF";
		int maxPostSize = 10 * 1024 * 1024;
		String message = affixService.uploadPicture(request, response, maxPostSize, affixType,path,agentId);
		
		if(message!=null){
			defaultPic = message;
			
		}
		map.put("defaultPic", defaultPic);
		map.put("picUrl", defaultPic);
		map.put("agentId", agentId);
		map.put("step", 2);
		return "users/uploadPage";
	}
	
	
	/**
	 * 保存被剪切的头像
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/saveCutImage")
	public void saveCutImage(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws Exception {
		String defaultPic = "/images/imageCut/man.GIF";
		String message = "";
		//系统路径
		String path = request.getSession().getServletContext().getRealPath("/");
		int imageWidth = Integer.parseInt(request.getParameter("txt_width"));
		int imageHeight = Integer.parseInt(request.getParameter("txt_height"));
		int cutTop = Integer.parseInt(request.getParameter("txt_top"));
		int cutLeft = Integer.parseInt(request.getParameter("txt_left"));
		int dropWidth = Integer.parseInt(request.getParameter("txt_DropWidth"));
		int dropHeight = Integer.parseInt(request.getParameter("txt_DropHeight"));
		
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		String agentId = user.getUserAgentId();
		String picture = request.getParameter("picture");
		
		if(defaultPic.equals(picture)){
			message = "n";
		}
		
		
		File file = new File((new StringBuilder(path)).append("/User").append(picture).toString());
		if (!file.exists()) {// 如果文件不存在,则创建目录
			file.mkdirs();
		}
		try {
			Rectangle rec = new Rectangle(cutLeft, cutTop, dropWidth, dropHeight);
			ImageHepler.cut(new File((new StringBuilder(path)).append(picture).toString()), file, imageWidth, imageHeight, rec);
		} catch (Exception e) {
			message = "n";
		}
		
		try {
			affixService.saveAffixPicture(request,response,affixType,agentId,"/User"+picture);
		} catch (Exception e) {
			message = "n";
		}
		response.setContentType("text/json");
		
		PrintWriter out = response.getWriter();
		JSONObject jo = new JSONObject();
		jo.put("result", message);
		jo.put("step", 3);
		jo.put("defaultPic","/User"+picture);
		out.print(jo.toString());
		out.flush();
		out.close();
	}
}
